package com.shakespace.artofandroid.chapter12bitmapandcache

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import com.shakespace.artofandroid.R


/**
 * created by  shakespace
 * 2021/4/13  23:07
 */
class GalleyAdapter(val context: Context, val data: List<String>) : BaseAdapter() {
    inner class GalleryViewHolder(val image: ImageView)

    private var mIsGridViewIdle = true

    val imageLoader = ImageLoader.build(context)
    fun setIsGridViewIdle(mIsGridViewIdle: Boolean) {
        this.mIsGridViewIdle = mIsGridViewIdle
    }

    override fun getCount(): Int = data.size

    override fun getItem(position: Int): String = data[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var viewHolder: GalleryViewHolder?
        val view: View
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false)

            val imageView = view.findViewById(R.id.image) as ImageView
            viewHolder = GalleryViewHolder(imageView)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as GalleryViewHolder
        }

        val imageView: ImageView = viewHolder.image
        val url = getItem(position)

        if (url != imageView.tag?.toString()) {
            imageView.setImageDrawable(ColorDrawable(Color.GRAY))
        }

        if (mIsGridViewIdle) {
            imageView.tag = url;
            imageLoader.bindBitmap(
                url,
                imageView,
                imageView.measuredWidth,
                imageView.measuredWidth
            );
        }
        return view
    }
}
